# -*- coding: latin-1 -*-
from climber import Climber
from slope import Slope
from contest import Contest, ContestException
import sys
try:
 	import pygtk
  	pygtk.require("2.0")
except:
  	pass
try:
	import gtk
  	import gtk.glade
except:
	sys.exit(1)
	
import threading
	
class GUI(object):
	"""This is the GUI for the cassebras software. It's PyGTK GUI which use glade in order to describe the widgets."""

	def __init__(self,contest,mutex):
		print "debut GUI"
		self._contest_mutex = mutex
		self._competition = contest
		self.gladefile = "cassebras.glade"  
		self.wTree = gtk.glade.XML(self.gladefile,"Competition") 

		#Create our dictionay and connect it
		dic = {"competition_destroy" : gtk.main_quit
				, "ClAdd" : self.ClAdd
				, "CaAdd" : self.CaAdd
				, "SlAdd" : self.SlAdd
				, "ClimbingAdd" : self.ClimbingAdd
				, "ClRemove" : self.ClRemove
				, "CaRemove" : self.CaRemove
				, "SlRemove" : self.SlRemove
				, "ClimbingRemove" : self.ClimbingRemove
				, "ClEdit" : self.ClEdit
				}
		self.wTree.signal_autoconnect(dic)
#		gtk.main()
	
	def SlAdd(self, widget):
		"""Called when the user wants to add a slope"""
		#Cteate the dialog, show it, and store the results
		SlopeAdd = SlAddDialog();		
		result,newSlope = SlopeAdd.run()
		if (result == gtk.RESPONSE_OK):
			try:
				newSlope = int(newSlope)
				try :
					slope=Slope(newSlope)
					self._contest_mutex.acquire()
					self._competition.add_slope(slope)
					self._contest_mutex.release()
				except ContestException, e:
					self._contest_mutex.release()
					ErrorDialog(e.message)
					self.SlAdd(widget)
			except ValueError,e:
				ErrorDialog('le numéro doit être un numéro')
				self.SlAdd(widget)
		
	def CaAdd(self, widget):
		"""Called when the user wants to add a category"""
		#Cteate the dialog, show it, and store the results
		CategoryAdd = CaAddDialog();		
		result,newCategory = CategoryAdd.run()
		
		if (result == gtk.RESPONSE_OK):
			
			try :
				self._contest_mutex.acquire()
				self._competition.add_category(newCategory)
				self._contest_mutex.release()
			except ContestException, e:
				self._contest_mutex.release()
				ErrorDialog(e.message)
				self.CaAdd(widget)

	def ClAdd(self, widget):
		"""Called when the user wants to add a climber"""
		#Cteate the dialog, show it, and store the results
		ClimberAdd = ClAddDialog(self._competition.categories);		
		result,newClimber = ClimberAdd.run()
		
		if (result == gtk.RESPONSE_OK):
			try:
				newClimber.id = int(newClimber.id)
				if newClimber.name == "":
					ErrorDialog('Le champ prénom doit être rempli')
					self.ClAdd(widget)
				else :
					if newClimber.fullname == "":	
						ErrorDialog('le champ nom doit être rempli')
						self.ClAdd(widget)		
					else:							
						try :
							self._contest_mutex.acquire()
							self._competition.add_climber(newClimber)
							self._contest_mutex.release()
						except ContestException, e:
							self._contest_mutex.release()
							ErrorDialog(e.message)
							self.ClAdd(widget)
				
			except ValueError,e:
				ErrorDialog('le numéro doit être un.... numéro')
				self.ClAdd(widget)
						
	def ClimbingAdd(self, widget):
		"""Called when the user wants to add a climbing"""
		#Cteate the dialog, show it, and store the results
		ClimbingAdd= ClimbingAddDialog();		
		result,ClId, SlId = ClimbingAdd.run()
		
		if (result == gtk.RESPONSE_OK):
			try:
				ClId = int(ClId)
				try:
					SlId = int(SlId)
					try :
						self._contest_mutex.acquire()
						self._competition.add_climbing(ClId, SlId)
						self._contest_mutex.release()
					except ContestException, e:
						self._contest_mutex.release()
						ErrorDialog(e.message)
						self.ClimbingAdd(widget)
				except ValueError,e:
					ErrorDialog('le numéro doit être un ..... numéro')
					self.ClimbingAdd(widget)
			except ValueError,e:
				ErrorDialog('le numéro doit être un ..... numéro')
				self.ClimbingAdd(widget)


	def ClRemove(self, widget):
		"""Called when the user wants to remove a climber"""
		#Cteate the dialog, show it, and store the results
		ClimberRemove= ClRemoveDialog();		
		result,ClId = ClimberRemove.run()
		
		if (result == gtk.RESPONSE_OK):
			try:
				ClId = int(ClId)
				try :
					self._contest_mutex.acquire()
					self._competition.remove_climber(ClId)
					self._contest_mutex.release()
				except ContestException, e:
					self._contest_mutex.release()
					ErrorDialog(e.message)
					self.ClRemove(widget)
			except ValueError,e:
				ErrorDialog('le numéro doit être un ..... numéro')
				self.ClRemove(widget)
			
	
	def CaRemove(self, widget):
		"""Called when the user wants to remove a slope"""
		#Cteate the dialog, show it, and store the results
		CategoryRemove= CaRemoveDialog(self._competition.categories);		
		result,CaId = CategoryRemove.run()
		
		if (result == gtk.RESPONSE_OK):
			
			try :
				self._contest_mutex.acquire()
				self._competition.remove_category(CaId)
				self._contest_mutex.release()
			except ContestException, e:
				self._contest_mutex.release()
				ErrorDialog(e.message)
				self.CaRemove(widget)
		
	def SlRemove(self, widget):
		"""Called when the user wants to remove a slope"""
		#Cteate the dialog, show it, and store the results
		SlopeRemove= SlRemoveDialog();		
		result,SlId = SlopeRemove.run()
		
		if (result == gtk.RESPONSE_OK):
			print"reponse OK"
			try:
				SlId = int(SlId)
				try :
					self._contest_mutex.acquire()
					self._competition.remove_slope(SlId)
					self._contest_mutex.release()
				except ContestException, e:
					self._contest_mutex.release()
					ErrorDialog(e.message)
					self.SlRemove(widget)
			except ValueError,e:
				ErrorDialog('le numéro doit être un ..... numéro')
				self.SlRemove(widget)
		else:
			print"reponse annuler"
		

	def ClimbingRemove(self, widget):
		"""Called when the user wants to remove a climbing"""
		#Cteate the dialog, show it, and store the results
		ClimbingRemove= ClimbingRemoveDialog();		
		result,ClId, SlId = ClimbingRemove.run()
		
		if (result == gtk.RESPONSE_OK):
			try:
				ClId = int(ClId)
				try:
					SlId = int(SlId)
					try :
						self._contest_mutex.acquire()
						self._competition.remove_climbing(ClId, SlId)
						self._contest_mutex.release()
					except ContestException, e:
						self._contest_mutex.release()
						ErrorDialog(e.message)
						self.ClimbingRemove(widget)
				except ValueError,e:
					ErrorDialog('le numéro doit être un ..... numéro')
					self.Climbingemove(widget)
			except ValueError,e:
				ErrorDialog('le numéro doit être un ..... numéro')
				self.ClimbingRemove(widget)
				
	def ClEdit(self, widget):
		"""Called when the user wants to remove a slope"""
		#Cteate the dialog, show it, and store the results
		ClEdit= ClEditDialog1();		
		result,ClId = ClEdit.run()
		if (result == gtk.RESPONSE_OK):
			try:
				ClId = int(ClId)
				if ClId not in self._competition.climbers.keys():
					ErrorDialog("Le grimpeur n'existe pas")
				else:
					ClEdit= ClEditDialog2(self._competition.climbers[ClId],self._competition.categories);		
					result,editClimber = ClEdit.run()
					if (result == gtk.RESPONSE_OK):
						if editClimber.name == "":
							ErrorDialog('le champ prénom doit être rempli')
							self.ClEditDialog2(widget,self._competition.climbers[ClId])
						else :
							if editClimber.fullname == "":	
								ErrorDialog('le champ nom doit être rempli')
								self.ClEditDialog2(widget,self._competition.climbers[ClId])		
							else:						
									self._contest_mutex.acquire()
									self._competition.climbers[ClId].age=editClimber.age
									self._competition.climbers[ClId].sexe=editClimber.sexe
									self._competition.climbers[ClId].name=editClimber.name
									self._competition.climbers[ClId].fullname=editClimber.fullname
									self._competition.climbers[ClId].category=editClimber.category
									self._contest_mutex.release()
			except ValueError,e:
				ErrorDialog('le numéro doit être un ..... numéro')
				self.ClEditDialog2(widget,ClId)
			

class ErrorDialog:
	"""This class is used to show SlAddDlg"""
	
	def __init__(self,MessageError):
		#setup the glade file
		self.gladefile = "cassebras.glade"
		self.wTree = gtk.glade.XML(self.gladefile, "ErrorDlg") 
		#Get the actual dialog widget
		self.dlg = self.wTree.get_widget("ErrorDlg")
		#Get all of the Entry Widgets and set their text
		self.ErrorLabel = self.wTree.get_widget("ErrorLabel")
		self.ErrorLabel.set_text(MessageError)
		
		#run the dialog and store the response		
		self.result = self.dlg.run()
		
		#we are done with the dialog, destroy it
		self.dlg.destroy()

class SlAddDialog:
	"""This class is used to show SlAddDlg"""
	
	def __init__(self):
	
		#setup the glade file
		self.gladefile = "cassebras.glade"
		
	def run(self):
		
		#load the dialog from the glade file	  
		self.wTree = gtk.glade.XML(self.gladefile, "SlAddDlg") 
		#Get the actual dialog widget
		self.dlg = self.wTree.get_widget("SlAddDlg")
		
		self.id=""
		#Get all of the Entry Widgets and set their text
		self.SlId = self.wTree.get_widget("SlId")
		self.SlId.set_text(self.id)
		
		#run the dialog and store the response		
		self.result = self.dlg.run()
		self.id = self.SlId.get_text()
	
		#we are done with the dialog, destory it
		self.dlg.destroy()
		
		#return the name of the new slope
		return self.result,self.id

class ClEditDialog1:
	"""This class is used to show ClAddDlg"""
	
	def __init__(self):
		#setup the glade file
		self.gladefile = "cassebras.glade"
		
	def run(self):
		#load the dialog from the glade file	  
		self.wTree = gtk.glade.XML(self.gladefile, "ClEditDlg1") 
		#Get the actual dialog widget
		self.dlg = self.wTree.get_widget("ClEditDlg1")
		
		self.id=""
		#Get all of the Entry Widgets and set their text
		self.ClId = self.wTree.get_widget("ClId")
		self.ClId.set_text(self.id)
		
		#run the dialog and store the response		
		self.result = self.dlg.run()
		self.id = self.ClId.get_text()
	
		#we are done with the dialog, destory it
		self.dlg.destroy()
		
		#return the name of the new slope
		return self.result,self.id
		
class ClEditDialog2:
	"""This class is used to show ClAddDlg"""
	
	def __init__(self, _climber,CategoryList):
	
		#setup the glade file
		self.gladefile = "cassebras.glade"
		self.climber=Climber(_climber.name, _climber.fullname, _climber.id, _climber.age, _climber.sexe, _climber.category)
		self.CaList=CategoryList
	def run(self):
			
		#load the dialog from the glade file	  
		self.wTree = gtk.glade.XML(self.gladefile, "ClEditDlg2") 
		#Get the actual dialog widget
		self.dlg = self.wTree.get_widget("ClEditDlg2")
		#Get all of the Entry Widgets and set their text
		self.ClName = self.wTree.get_widget("ClName")
		self.ClName.set_text(self.climber.name)
		self.ClFullName = self.wTree.get_widget("ClFullName")
		self.ClFullName.set_text(self.climber.fullname)
		self.ClAge = self.wTree.get_widget("ClAge")
		self.ClAge.set_text(str(self.climber.age))
		self.ClSex = self.wTree.get_widget("ClSexe")
		self.ClSex.set_text(self.climber.sexe)	
		self.ClCategory = self.wTree.get_widget("ClCategory")
		self.ClCategory.set_text(self.climber.category)	
		completion=gtk.EntryCompletion()
		self.ClCategory.set_completion(completion)
		completion_model = self.__create_completion_model(self.CaList)
		completion.set_model(completion_model)
		completion.set_text_column(0)
		#run the dialog and store the response		
		self.result = self.dlg.run()
		#get the value of the entry fields
		self.climber.id = self.climber.id
		self.climber.name = self.ClName.get_text()
		self.climber.fullname = self.ClFullName.get_text()
		self.climber.category = self.ClCategory.get_text()
		self.climber.sexe = self.ClSex.get_text()
		self.climber.age = self.ClAge.get_text()		
		#we are done with the dialog, destory it
		self.dlg.destroy()
		
		#return the result and the climber
		return self.result,self.climber

	def __create_completion_model(self,completionList):
		''' Creates a tree model containing the completions.'''
		store = gtk.ListStore(str)
		for i in range(1,len(completionList)):
			iter = store.append()
			store.set(iter, 0, completionList[i])
			
		return store
		
class CaAddDialog:
	"""This class is used to show CaAddDlg"""
	
	def __init__(self, CaName=""):
	
		#setup the glade file
		self.gladefile = "cassebras.glade"
		
	def run(self):
		
		#load the dialog from the glade file	  
		self.wTree = gtk.glade.XML(self.gladefile, "CaAddDlg") 
		#Get the actual dialog widget
		self.dlg = self.wTree.get_widget("CaAddDlg")
		#Get all of the Entry Widgets and set their text
		self.CaName = self.wTree.get_widget("CaName")
		
		self.name=""
		self.CaName.set_text(self.name)		

		#run the dialog and store the response		
		self.result = self.dlg.run()
		self.name = self.CaName.get_text()
	
		#we are done with the dialog, destory it
		self.dlg.destroy()
		
		#return the name of the category
		return self.result,self.name

class ClAddDialog:
	"""This class is used to show ClAddDlg"""
	
	def __init__(self, CategoryList,ClId="", ClName="", ClFullName="", ClCategory="", ClAge="", ClSex=""):
	
		#setup the glade file
		self.gladefile = "cassebras.glade"
		self.climber = Climber(ClName, ClFullName, ClId, ClAge, ClSex, ClCategory)
		self.CaList=CategoryList
		
	def run(self):
			
		
		#load the dialog from the glade file	  
		self.wTree = gtk.glade.XML(self.gladefile, "ClAddDlg") 
		#Get the actual dialog widget
		self.dlg = self.wTree.get_widget("ClAddDlg")
		#Get all of the Entry Widgets and set their text
		self.ClId = self.wTree.get_widget("ClId")
		self.ClId.set_text(self.climber.id)
		self.ClName = self.wTree.get_widget("ClName")
		self.ClName.set_text(self.climber.name)
		self.ClFullName = self.wTree.get_widget("ClFullName")
		self.ClFullName.set_text(self.climber.fullname)
		self.ClAge = self.wTree.get_widget("ClAge")
		self.ClAge.set_text(self.climber.age)	
		self.ClSex = self.wTree.get_widget("ClSex")
		self.ClSex.set_text(self.climber.sexe)	
		self.ClCategory = self.wTree.get_widget("ClCategory")
		self.ClCategory.set_text(self.climber.category)	
		completion=gtk.EntryCompletion()
		self.ClCategory.set_completion(completion)
		completion_model = self.__create_completion_model(self.CaList)
		completion.set_model(completion_model)
		completion.set_text_column(0)
	
		#run the dialog and store the response		
		self.result = self.dlg.run()
		#get the value of the entry fields
		self.climber.id = self.ClId.get_text()
		self.climber.name = self.ClName.get_text()
		self.climber.fullname = self.ClFullName.get_text()
		self.climber.category = self.ClCategory.get_text()
		self.climber.sexe = self.ClSex.get_text()
		self.climber.age = self.ClAge.get_text()
		
		
		#we are done with the dialog, destory it
		self.dlg.destroy()
		
		#return the result and the climber
		return self.result,self.climber
		
	def __create_completion_model(self,completionList):
		''' Creates a tree model containing the completions.'''
		store = gtk.ListStore(str)
		for i in range(1,len(completionList)):
			iter = store.append()
			store.set(iter, 0, completionList[i])
			
		return store


class ClRemoveDialog:

	def run(self):
		#load the dialog from the glade file	  
		self.wTree = gtk.glade.XML(self.gladefile, "ClRemoveDlg") 
		#Get the actual dialog widget
		self.dlg = self.wTree.get_widget("ClRemoveDlg")
		
		self.id=""
		#Get all of the Entry Widgets and set their text
		self.ClId = self.wTree.get_widget("ClId")
		self.ClId.set_text(str(self.id))
		
		
		#run the dialog and store the response		
		self.result = self.dlg.run()
		self.id = self.ClId.get_text()
	
		#we are done with the dialog, destory it
		self.dlg.destroy()
		
		#return the name of the new slope
		return self.result,self.id

	def __init__(self):
	
		#setup the glade file
		self.gladefile = "cassebras.glade"
		
class CaRemoveDialog:

	def run(self):
		#load the dialog from the glade file	  
		self.wTree = gtk.glade.XML(self.gladefile, "CaRemoveDlg") 
		#Get the actual dialog widget
		self.dlg = self.wTree.get_widget("CaRemoveDlg")
		
		self.id=""
		#Get all of the Entry Widgets and set their text
		self.CaId = self.wTree.get_widget("CaId")
		self.CaId.set_text(self.id)
		completion=gtk.EntryCompletion()
		self.CaId.set_completion(completion)
		completion_model = self.__create_completion_model(self.CaList)
		completion.set_model(completion_model)
		completion.set_text_column(0)
		
		#run the dialog and store the response		
		self.result = self.dlg.run()
		self.id = self.CaId.get_text()
	
		#we are done with the dialog, destory it
		self.dlg.destroy()
		
		#return the name of the new slope
		return self.result,self.id

	def __init__(self,CategoryList):
	
		#setup the glade file
		self.gladefile = "cassebras.glade"	
		self.CaList=CategoryList
		
	def __create_completion_model(self,completionList):
		''' Creates a tree model containing the completions.'''
		store = gtk.ListStore(str)
		for i in range(1,len(completionList)):
			iter = store.append()
			store.set(iter, 0, completionList[i])
			
		return store
	
class SlRemoveDialog:

	def __init__(self):
	
		#setup the glade file
		self.gladefile = "cassebras.glade"
		
	def run(self):
		
		#load the dialog from the glade file	  
		self.wTree = gtk.glade.XML(self.gladefile, "SlRemoveDlg") 
		#Get the actual dialog widget
		self.dlg = self.wTree.get_widget("SlRemoveDlg")
		
		self.id=""
		#Get all of the Entry Widgets and set their text
		self.SlId = self.wTree.get_widget("SlId")
		self.SlId.set_text(self.id)
		
		#run the dialog and store the response		
		self.result = self.dlg.run()
		self.id = self.SlId.get_text()
	
		#we are done with the dialog, destory it
		self.dlg.destroy()
		
		#return the name of the new slope
		return self.result,self.id

class ClimbingRemoveDialog:

	def __init__(self):
	
		#setup the glade file
		self.gladefile = "cassebras.glade"
		
	def run(self):
		
		#load the dialog from the glade file	  
		self.wTree = gtk.glade.XML(self.gladefile, "ClimbingRemoveDlg") 
		#Get the actual dialog widget
		self.dlg = self.wTree.get_widget("ClimbingRemoveDlg")
		
		self.climber_id=""
		self.slope_id=""
		#Get all of the Entry Widgets and set their text
		self.SlId = self.wTree.get_widget("SlId")
		self.SlId.set_text(self.slope_id)
		self.ClId = self.wTree.get_widget("ClId")
		self.ClId.set_text(self.climber_id)
		#run the dialog and store the response		
		self.result = self.dlg.run()
		self.climber_id = self.ClId.get_text()
		self.slope_id = self.SlId.get_text()
		#we are done with the dialog, destory it
		self.dlg.destroy()

				
		return self.result,self.climber_id, self.slope_id


class ClimbingAddDialog:

	def __init__(self):
	
		#setup the glade file
		self.gladefile = "cassebras.glade"
		
	def run(self):
		
		#load the dialog from the glade file	  
		self.wTree = gtk.glade.XML(self.gladefile, "ClimbingAddDlg") 
		#Get the actual dialog widget
		self.dlg = self.wTree.get_widget("ClimbingAddDlg")
		
		self.climber_id=""
		self.slope_id=""
		#Get all of the Entry Widgets and set their text
		self.SlId = self.wTree.get_widget("SlId")
		self.SlId.set_text(self.slope_id)
		self.ClId = self.wTree.get_widget("ClId")
		self.ClId.set_text(self.climber_id)
		#run the dialog and store the response		
		self.result = self.dlg.run()
		self.climber_id = self.ClId.get_text()
		self.slope_id = self.SlId.get_text()
		#we are done with the dialog, destory it
		self.dlg.destroy()
	
				
		return self.result,self.climber_id, self.slope_id		
	

if __name__ == "__main__":
	contest=Contest()
	mutex = threading.Semaphore()
	gui = GUI(contest,mutex)
	gtk.main()
